import express from 'express';
import aiService from '../services/aiService.js';
import { authenticateToken } from '../middleware/auth.js';

const router = express.Router();

// AI聊天接口
router.post('/chat', authenticateToken, async (req, res) => {
  try {
    const { message } = req.body;
    const userId = req.user.id;
    
    if (!message) {
      return res.status(400).json({
        success: false,
        message: '消息不能为空'
      });
    }
    
    console.log('AI chat request:', { userId, message });
    
    // 设置超时处理
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时，请稍后再试')), 30000);
    });
    
    // 使用 Promise.race 处理超时
    const result = await Promise.race([
      aiService.chat(message, userId),
      timeoutPromise
    ]);
    
    res.json(result);
  } catch (error) {
    console.error('Chat error:', error);
    
    // 根据错误类型返回不同的状态码和消息
    if (error.message.includes('超时')) {
      res.status(504).json({
        success: false,
        message: error.message,
        error: process.env.NODE_ENV === 'production' ? {} : error
      });
    } else {
      res.status(500).json({
        success: false,
        message: '聊天服务暂时不可用',
        error: process.env.NODE_ENV === 'production' ? {} : error
      });
    }
  }
});

// 获取聊天历史
router.get('/history', authenticateToken, async (req, res) => {
  try {
    const history = await aiService.getChatHistory(req.user.id);
    res.json({
      success: true,
      data: history
    });
  } catch (error) {
    console.error('Error fetching chat history:', error);
    res.status(500).json({
      success: false,
      message: '获取聊天历史失败'
    });
  }
});

// 获取商品推荐
router.get('/recommendations', authenticateToken, async (req, res) => {
  try {
    const userBehavior = {
      viewHistory: req.query.viewHistory?.split(',') || [],
      purchaseHistory: req.query.purchaseHistory?.split(',') || [],
      favorites: req.query.favorites?.split(',') || []
    }

    const result = await aiService.getProductRecommendations(
      req.user.id,
      userBehavior
    )

    res.json(result)
  } catch (error) {
    console.error('Error getting recommendations:', error)
    res.status(500).json({
      success: false,
      message: '获取推荐失败'
    })
  }
});

export default router; 